package Dao;


import entity.Sc;
import utils.JdbcUtils_DBCP;


import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author DONG
 */
public class ScDaoImpl implements ScDao {
    @Override
    public boolean saveSc(String id,int sc,String gameType) {
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = JdbcUtils_DBCP.getConnection();
            //?是占位符 代替参数
            String sql = "insert into  Scores (SId, UId, Score, GameType)VALUES(?,?,?,?);";
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // new Date()为获取当前系统时间
            String sId = df.format(new Date());
            //预编译sql 先写sql 但是不执行
            st = conn.prepareStatement(sql);
            //手动给参数赋值

            st.setString(1, sId);
            st.setString(2, id);
            st.setInt(3, sc);
            st.setString(4, gameType);


            //以上填充完毕 然后执行
            int i = st.executeUpdate();
            if (i > 0) {
                System.out.println("成绩插入成功");
                return true;
            }else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_DBCP.release(conn, st, null);
        }
        return false;
    }

    @Override
    public List<Sc> queryAllSc() {
        List<Sc> sCS = new ArrayList<Sc>();
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet re;
        try {
            conn = JdbcUtils_DBCP.getConnection();
            //?是占位符 代替参数
            String sql = "select * from Scores Where GameType = 'Snack' \n" +
                    "ORDER BY SCore DESC limit 0,10;";
            st = conn.prepareStatement(sql);
            re = st.executeQuery();
            while (re.next()){
                String sid = re.getString("SId");
                String uid = re.getString("UID");
                String score = re.getString("Score");
                String gameType = re.getString("GameType");
                Sc sc = new Sc(sid, uid, score, gameType);
                sCS.add(sc);
            }
            return sCS;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_DBCP.release(conn, st, null);
        }

        return null;
    }
}
